package com.lebang.controller.api.task;

import com.lebang.aop.Sessionid;
import com.lebang.common.AllMemberLock;
import com.lebang.common.Require;
import com.lebang.common.util.JsonDataUtil;
import com.lebang.common.util.RequestUtil;
import com.lebang.common.util.ShowDateUtil;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.member.LbbMemberRecord;
import com.lebang.entity.task.TaskComments;
import com.lebang.entity.task.TaskCommentsDetail;
import com.lebang.entity.task.TaskScreenshot;
import com.lebang.model.enums.Status;
import com.lebang.model.enums.TaskEnableResultEnum;
import com.lebang.model.enums.buss.RecordStatus;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.model.enums.buss.TaskStatus;
import com.lebang.model.taskback.CommonCallBack;
import com.lebang.service.TaskInRedisService;
import com.lebang.service.TaskScreenshotService;
import com.lebang.service.buss.CommentDetailService;
import com.lebang.service.buss.CustomService;
import com.lebang.service.buss.MemberRecordService;
import com.lebang.service.buss.MemberService;
import com.lebang.service.task.TaskService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.lebang.service.task.impl.CommentsServiceImpl.TASK_COMMENTS_AMOUNT;

/**
 * @Author: hwq
 * @Date: 2019/8/6 10:42
 * @Version 1.0
 * 评论任务app接口
 */
@RestController
public class CommentsApi {
    @Autowired
    private TaskService<TaskComments> taskService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberRecordService memberRecordService;
    @Autowired
    private CommentDetailService detailService;
    @Autowired
    private TaskInRedisService taskInRedisService;
    @Autowired
    private TaskScreenshotService taskScreenshotService;
    @Autowired
    private CustomService customService;

    /**
     * 任务详情
     *
     * @param taskid
     * @param request
     * @param response
     * @return
     */

    @Require
    @Sessionid
    @RequestMapping(value = {"/task/comments/{taskid}", "/task/Comments/{taskid}"}, method = {RequestMethod.GET})
    public JsonData detail(@PathVariable(value = "taskid") String taskid, HttpServletRequest request,
                           HttpServletResponse response) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        try {
            String userid = requestHeaders.getUserid();
            userid = userid == null ? "" : userid;
            LbbMember member = memberService.getMemberByMemberId(userid);
            // 获取任务信息
            TaskComments task = taskService.taskInfoByTaskId(taskid);
            // 任务是否存在
            if (task == null) {
                return Callback.fail("empty", "任务不存在！");
            }
            // 下架任务不能访问
//            if (Status.Off.getIndex() == task.getStatus()) {
//                return Callback.fail("offline", "任务已下架！");
//            }
            LbbMemberRecord record = memberRecordService.checkRecord(userid, taskid, TaskCategory.Comments.name());
            CommonCallBack commonCallBack = taskService.taskDetail(task, record, member, "");
            Map map = new HashMap<String, Object>(1);
            if (record != null) {
                TaskCommentsDetail detail = detailService.selectById(record.getOrderId());
                if (TextUtil.isEmpty(detail.getPicture())) {
                    detail.setHasPicture(false);
                } else {
                    detail.setHasPicture(true);
                    List<String> stringList = Arrays.asList(detail.getPicture().split("#"));
                    detail.setPictureList(stringList);
                }
                map.put("detail", detail);
            } else {
                map.put("detail", "");
            }
            TaskScreenshot taskScreenshot = taskScreenshotService.selectByTaskId(taskid);
            if (record==null){
                commonCallBack.setRedocount(0);
                commonCallBack.setNumber(taskScreenshot.getFailTimes());
                commonCallBack.setQq("");
                commonCallBack.setIsTime(0);
            }else {
                if (isOverTime(record.getCreateTime(),taskScreenshot.getReleaseTime())){
                    commonCallBack.setIsTime(1);
                }
                commonCallBack.setRedocount(record.getRedo());
                commonCallBack.setNumber(taskScreenshot.getFailTimes()-record.getRedo());
                commonCallBack.setQq(Optional.ofNullable(customService.selectByCustomId(taskScreenshot.getCustomer())).orElse(""));
            }
            commonCallBack.setShareIntroduce(taskScreenshot.getShareIntroduce());
            map.put("data", commonCallBack);

            return Callback.success("success", "已返回任务详情！", map);
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
    }

    //是否超时
    public Boolean isOverTime(Date time, Integer releaseTime) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (releaseTime == null) {
            releaseTime = 30;
        }
        LocalDateTime overtime = LocalDateTime.parse(ShowDateUtil.afterMinute(time, releaseTime), df);
        if (LocalDateTime.now().isAfter(overtime)) {
            return true;
        }
        return false;
    }
    /**
     * 领取任务
     *
     * @param taskid
     * @param request
     * @param response
     * @return
     * @author weizx
     * @date 2018年7月20日 下午9:30:26
     */
    @Sessionid
    @Require
    @RequestMapping(value = {"/pull/comments/{taskid}", "/pull/Comments/{taskid}"}, method = {RequestMethod.POST})
    @AllMemberLock
    public JsonData pull(@PathVariable("taskid") String taskid,
                         @RequestParam(value = "orderid", required = false) String orderid, HttpServletRequest request,
                         HttpServletResponse response) {
        try {
            RequestHeaders requestHeader = RequestUtil.getHeader(request);
            // 获取任务信息
            TaskComments task = taskService.taskInfoByTaskId(taskid);
            if (task == null) {
                // 任务是否存在
                return Callback.fail("empty", "任务不存在！");
            }
            // 校验任务是否可以被领取
            TaskEnableResultEnum checkResult = taskService.checkTaskEnableDoForUser(taskid, requestHeader.getImei(), requestHeader.getUserid());
            if (!checkResult.equals(TaskEnableResultEnum.SUCCESS)) {
                return Callback.fail(checkResult.getStatus(), checkResult.getMsg(), null);
            }
            RecordStatus status = null;
            //领取任务
            status = taskService.pull(requestHeader.getUserid(), task, requestHeader, orderid,task.getTaskId());
            if (status.isStatus()) {
                LbbMemberRecord record = memberRecordService.checkRecord(requestHeader.getUserid(), task.getTaskId(), TaskCategory.Comments.name());
                TaskCommentsDetail detail = detailService.selectById(record.getOrderId());
                return Callback.success("success", status.getMsg(), detail);
            } else {
                return JsonDataUtil.toJsonData(status);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
    }

    /**
     * 提交任务
     */
    @Require
    @Sessionid
    @RequestMapping(value = {"/push/comments/{taskid}", "/push/Comments/{taskid}"}, method = {RequestMethod.POST})
    @AllMemberLock
    public JsonData push(@PathVariable("taskid") String taskid,
                         @RequestParam(value = "orderid", required = false) String orderid,
                         @RequestParam(value = "result", required = false) String result, HttpServletRequest request,
                         HttpServletResponse response, Integer sex) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        try {
            String userid = requestHeaders.getUserid();
            userid = userid == null ? "" : userid;
            // 获取任务信息
            TaskComments task = taskService.taskInfoByTaskId(taskid);
            if (task == null) {
                // 任务是否存在
                return Callback.fail("empty", "任务不存在！");
            }
            // 用户是否领取
            LbbMemberRecord record = memberRecordService.checkRecord(userid, taskid, TaskCategory.Comments.name());
            if (record == null) {
                return Callback.fail("empty", "亲，您还未领取该任务！");
            }
            // 任务是否是待提交
            if (!TaskStatus.WaitSumbit.equals(record.getStatus())) {
                return Callback.fail("sorry", "亲，您已完成过该任务！");
            }
            if (null == result || "".equals(result)) {
                return Callback.fail("invalid", "亲，请先提交审核材料！");
            } else {
                //提交任务
                RecordStatus status = taskService.push(userid, record, task, result, sex);
                return JsonDataUtil.toJsonData(status);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
    }

    /**
     * 重做任务
     */
    @Require
    @Sessionid
    @RequestMapping(value = {"/comments/redo"}, method = {RequestMethod.POST})
    @AllMemberLock
    public JsonData redo(HttpServletRequest request, String taskid) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String userid = requestHeaders.getUserid();
        userid = userid == null ? "" : userid;
        // 获取任务信息
        TaskComments task = taskService.taskInfoByTaskId(taskid);
        if (task == null) { // 任务是否存在
            return Callback.fail("fail", "任务不存在！");
        }
        if (task.getRedo() == null) {
            return Callback.fail("fail", "该任务不可重做！");
        }
        if (task.getRedo() != 1) {
            return Callback.fail("fail", "该任务不可重做！");
        }
        // 用户是否领取
        LbbMemberRecord record = memberRecordService.checkRecord(userid, taskid, null);
        if (record == null) {
            return Callback.fail("fail", "亲，您还未领取该任务！");
        }

        if (!record.getStatus().equals(TaskStatus.CheckFailure)) {
            return Callback.fail("empty", "只能重做失败状态的任务！");
        }

        int count = taskInRedisService.getTaskAmount(TASK_COMMENTS_AMOUNT, task.getTaskId());

        if (count <= 0) {
            return Callback.fail("empty", "任务已经被抢完了,明天再来吧~");
        }
        //重做任务
        RecordStatus status = taskService.redo(userid, record, task);
        return JsonDataUtil.toJsonData(status);
    }

    /**
     * 催审
     */
    @Require
    @Sessionid
    @RequestMapping(value = {"/comments/task"}, method = {RequestMethod.POST})
    @AllMemberLock
    public JsonData task(HttpServletRequest request, String taskid) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String userid = requestHeaders.getUserid();
        userid = userid == null ? "" : userid;
        // 获取任务信息
        TaskComments task = taskService.taskInfoByTaskId(taskid);
        if (task == null) {
            // 任务是否存在
            return Callback.fail("fail", "任务不存在！");
        }
        if (task.getAuditTime() == null) {
            return Callback.fail("fail", "催审失败!未设置审核时间！");
        }
        LbbMemberRecord record = memberRecordService.checkRecord(userid, taskid, null);
        if (!record.getStatus().equals(TaskStatus.WaitCheckout)) {
            return Callback.fail("fail", "催审失败!该任务不处于待审核状态！");
        }
        // 催审
        RecordStatus status = taskService.urgentTask(userid, record, task);
        return JsonDataUtil.toJsonData(status);
    }
}
